package servlet;

import bean.User;
import dao.UserDao;
import util.JsonWrapper;
import util.ResponseUtil;
import util.SMSUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 骑行用户注册
 *
 * @author 邓晴予
 */
public class UserRegisterServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		获取用户名密码
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");
        String messageCode = req.getParameter("messageCode");
        User user = new User();
        user.setPassword(password);
        user.setPhone(phone);
        user.setUserName(phone);
        JsonWrapper result = new JsonWrapper();
//		短信验证码验证
        int isSuccess = SMSUtils.checkSMSCode(req, resp, phone, messageCode);
        if (SMSUtils.CHECK_RESULT_FALSE == isSuccess) {
//			验证码不正确
            result.setStatus(301);
            result.setMsg("failed");
        } else if (SMSUtils.CHECK_RESULT_INVALID == isSuccess) {
//			验证码失效
            result.setStatus(302);
            result.setMsg("failed");
        } else {
//			手机号唯一性检查
            if (userDao.phoneExist(phone)) {
//				手机号已存在
                result.setStatus(300);
                result.setMsg("failed");
            } else {
                try {
                    user.setScore("0");
                    user.setBalance("0.0");
                    user.setStatus("1");
                    if (userDao.userAdd(user)) {
//						添加成功
                        result.setStatus(200);
                        result.setMsg("success");
                    } else {
//						添加失败
                        result.setStatus(403);
                        result.setMsg("failed");
                    }
                } catch (Exception e) {
                    result.setStatus(401);
                    result.setMsg("failed");
                }
            }
//  }
        }
        ResponseUtil.write(resp, result);
    }
}
